"""
Case Type   : 基础功能
Case Name   : 创建表，创建序列属于同一用户，序列owned by关联表字段
Create At   : 2023/05/08
Owner       : cr13
Description :
    1.建表
    2.创建序列
    3.nextval查询序列值
    4.清理环境
Expect      :
    1.成功
    2.成功
    3.成功
    4.成功
History     :
"""
import os
import unittest
from testcase.utils.CommonSH import CommonSH
from testcase.utils.Constant import Constant
from testcase.utils.Logger import Logger


class SQL(unittest.TestCase):
    def setUp(self):
        self.log = Logger()
        self.log.info(f'----{os.path.basename(__file__)} start----')
        self.constant = Constant()
        self.comshpri = CommonSH('PrimaryDbUser')
        self.tb_name = "t_ddl_sequence_037"
        self.sequence = "s_ddl_sequence_037"
        self.user = "u_ddl_sequence_037"

    def test_create_sequence(self):
        text = '----step1:建表 expect:成功----'
        self.log.info(text)
        sql_cmd = f"drop table if exists {self.tb_name};create table " \
            f"{self.tb_name}(id int,name text);"
        result = self.comshpri.execut_db_sql(sql_cmd)
        self.log.info(result)
        self.assertIn(self.constant.TABLE_DROP_SUCCESS, result, '执行失败'
                      + text)
        self.assertIn(self.constant.CREATE_TABLE_SUCCESS, result, '执行失败' +
                      text)

        text = '----step2:创建序列 expect:成功----'
        self.log.info(text)
        sql_cmd = f"drop sequence if exists {self.sequence};create sequence " \
            f"{self.sequence} owned by {self.tb_name}.id;"
        result = self.comshpri.execut_db_sql(sql_cmd)
        self.log.info(result)
        self.assertIn(self.constant.DROP_SEQUENCE_SUCCESS_MSG, result,
                      '执行失败' + text)
        self.assertIn(self.constant.CREATE_SEQUENCE_SUCCESS_MSG, result,
                      '执行失败' + text)

        text = '----step3:nextval查询序列值 expect:成功----'
        self.log.info(text)
        sql_cmd = f"select nextval('{self.sequence}');"
        result = self.comshpri.execut_db_sql(sql_cmd)
        self.log.info(result)
        self.assertEqual(str(str(result).splitlines()[-2]).strip(), '1',
                         '执行失败' + text)

    def tearDown(self):
        text = "----step4:环境清理 expect:成功----"
        self.log.info(text)
        result = self.comshpri.execut_db_sql(
            f"drop table if exists {self.tb_name} cascade;")
        self.log.info(result)
        self.assertIn(self.constant.TABLE_DROP_SUCCESS, result, '执行失败'
                      + text)
        self.log.info(f'-----{os.path.basename(__file__)} end-----')
